/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.core;

import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.util.StringValueResolver;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Simple implementation of the {@link AliasRegistry} interface.
 * Serves as base class for
 * {@link org.springframework.beans.factory.support.BeanDefinitionRegistry}
 * implementations.
 *
 * @author Juergen Hoeller
 * @since 2.5.2
 */
public class SimpleAliasRegistry implements AliasRegistry {

	/**
	 * Map from alias to canonical name
	 *
	 * 从 别名 映射 到 规范名称
	 * （别名作为键，规范名称作为值）
	 * alias, registeredName
	 */
	private final Map<String, String> aliasMap = new ConcurrentHashMap<>(16);

	/**
	 * TODO:需要关注本类中 registerAlias() 注册别名
	 *
	 * @param name the canonical name
	 * @param alias the alias to be registered999
	 */
	@Override
	public void registerAlias(String name, String alias) {
		Assert.hasText(name, "'name' must not be empty");
		Assert.hasText(alias, "'alias' must not be empty");
		//1.如果传参中的 名称=别名 ——> 不进行注册 + 移除已注册的别名
		if (alias.equals(name)) {
			this.aliasMap.remove(alias);
		}
		else {
			String registeredName = this.aliasMap.get(alias);
			if (registeredName != null) {
				///2.如果存在别名相同的注册
				///注册名称相同 ——> 不处理（重新注册）直接返回
				if (registeredName.equals(name)) {
					// An existing alias - no need to re-register
					return;
				}
				///如果注册名称不同 ——> 需要根据 是否允许别名重写（allowAliasOverriding()）进行判断
				if (!allowAliasOverriding()) {
					throw new IllegalStateException("Cannot register alias '" + alias + "' for name '" +
							name + "': It is already registered for name '" + registeredName + "'.");
				}
			}
			///3.注册前检查是否出现了循环注册，如注册 (a, b) 时已经注册了 (b, a)就会抛出异常
			checkForAliasCircle(name, alias);
			///4.可能发生覆盖（同一个别名-key，但是注册名称-value 被覆盖了）
			this.aliasMap.put(alias, name);
		}
	}

	/**
	 * Return whether alias overriding is allowed.
	 * Default is {@code true}.
	 */
	protected boolean allowAliasOverriding() {
		return true;
	}

	/**
	 * Determine whether the given name has the given alias registered.
	 *
	 * TODO:判断是否有别名
	 * 确认 给定的名称是否已经注册了给定的别名
	 * （会递归进行判断，同个注册名称下的别名集合中，是否存在他们新的键值对？待验证）
	 *
	 * @param name the name to check
	 * @param alias the alias to look for
	 * @since 4.2.1
	 */
	public boolean hasAlias(String name, String alias) {
		for (Map.Entry<String, String> entry : this.aliasMap.entrySet()) {
			String registeredName = entry.getValue();
			if (registeredName.equals(name)) {
				String registeredAlias = entry.getKey();
				return (registeredAlias.equals(alias) || hasAlias(registeredAlias, alias));
			}
		}
		return false;
	}

	@Override
	public void removeAlias(String alias) {
		String name = this.aliasMap.remove(alias);
		if (name == null) {
			throw new IllegalStateException("No alias '" + alias + "' registered");
		}
	}

	@Override
	public boolean isAlias(String name) {
		return this.aliasMap.containsKey(name);
	}

	/**
	 * TODO:获取制定 bean 的所有别名（递归）
	 * @param name the name to check for aliases
	 * @return
	 */
	@Override
	public String[] getAliases(String name) {
		List<String> result = new ArrayList<>();
		synchronized (this.aliasMap) {
			retrieveAliases(name, result);
		}
		return StringUtils.toStringArray(result);
	}

	/**
	 * Transitively retrieve all aliases for the given name.
	 *
	 * （传递的方式检索）
	 *
	 * @param name the target name to find aliases for
	 * @param result the resulting aliases list
	 */
	private void retrieveAliases(String name, List<String> result) {
		this.aliasMap.forEach((alias, registeredName) -> {
			if (registeredName.equals(name)) {
				result.add(alias);
				retrieveAliases(alias, result);
			}
		});
	}

	/**
	 * Resolve all alias target names and aliases registered in this
	 * factory, applying the given StringValueResolver to them.
	 * <p>The value resolver may for example resolve placeholders
	 * in target bean names and even in alias names.
	 *
	 * TODO:解析 alias 和 name 中的占位符。
	 *
	 * @param valueResolver the StringValueResolver to apply
	 */
	public void resolveAliases(StringValueResolver valueResolver) {
		Assert.notNull(valueResolver, "StringValueResolver must not be null");
		synchronized (this.aliasMap) {
			///因为遍历时需要改动集合，于是拷贝了一份 aliasCopy 用于遍历；
			///同时修改原有集合
			Map<String, String> aliasCopy = new HashMap<>(this.aliasMap);
			for (String alias : aliasCopy.keySet()) {
				String registeredName = aliasCopy.get(alias);
				String resolvedAlias = valueResolver.resolveStringValue(alias);
				String resolvedName = valueResolver.resolveStringValue(registeredName);
				/// 1.1 不存在 || resolvedAlias=resolvedName 时直接干掉
				if (resolvedAlias == null || resolvedName == null || resolvedAlias.equals(resolvedName)) {
					this.aliasMap.remove(alias);
				}
				///1.2 解析后的别名 ！= 原先的别名
				else if (!resolvedAlias.equals(alias)) {
					String existingName = this.aliasMap.get(resolvedAlias);
					///1.2.1 判断解析后的别名是否存在 注册名称
					///存在时 ——> 如果与解析后的名称相等，说明多余了，就把原先的别名移除即可！否则异常
					///？？？？但是有个问题，就是一个是解析后的，一个是不曾解析的。是否存在解析后就相等的情况？
					if (existingName != null) {
						if (existingName.equals(resolvedName)) {
							// Pointing to existing alias - just remove placeholder
							this.aliasMap.remove(alias);
							break;
						}
						///
						throw new IllegalStateException(
								"Cannot register resolved alias '" + resolvedAlias + "' (original: '" + alias +
								"') for name '" + resolvedName + "': It is already registered for name '" +
								registeredName + "'.");
					}
					///不存在 ——> 判断是否别名依赖，更新为解析后的 别名-注册名称（通过移除老的，添加新的实现！）
					checkForAliasCircle(resolvedName, resolvedAlias);
					this.aliasMap.remove(alias);
					this.aliasMap.put(resolvedAlias, resolvedName);
				}
				///1.3 如果注册名称 ！= 解析后的名称 （其实已经满足：解析后的别名 == 原先的别名）
				///——> 直接 put 进行更新！
				else if (!registeredName.equals(resolvedName)) {
					this.aliasMap.put(alias, resolvedName);
				}
			}
		}
	}

	/**
	 * Check whether the given name points back to the given alias as an alias
	 * in the other direction already, catching a circular reference upfront
	 * and throwing a corresponding IllegalStateException.
	 *
	 * 检查 给定的名称是否已作为另一个别名 指向给定的别名，
	 * 预先捕获循环引用 并抛出一个相应的 illegalStateException
	 * （首先利用 name 和 alias 倒置判断是否循环依赖）
	 *
	 * TODO:检查别名的循环依赖！
	 * @param name the candidate name
	 * @param alias the candidate alias
	 * @see #registerAlias
	 * @see #hasAlias
	 */
	protected void checkForAliasCircle(String name, String alias) {
		if (hasAlias(alias, name)) {
			throw new IllegalStateException("Cannot register alias '" + alias +
					"' for name '" + name + "': Circular reference - '" +
					name + "' is a direct or indirect alias for '" + alias + "' already");
		}
	}

	/**
	 * Determine the raw name, resolving aliases to canonical names.
	 *
	 * TODO:获取真实名称（最终解析）/ bean 实例在容器里的真正名字
	 * 确定原始名称，将别名解析为规范名称。
	 * （这个方法用了 do while 循环，得到最终的注册名称。）
	 *
	 * @param name the user-specified name	（去掉 & 之后的名字）
	 * @return the transformed name 最终得到的不会是别名！而是原始名称！
	 */
	public String canonicalName(String name) {
		String canonicalName = name;
		// Handle aliasing...
		String resolvedName;
		do {
			// 根据别名获取真正的 beanName；为了找到 别名的别名 这种情况，就回进行递归，知道找到真正的 bean name
			resolvedName = this.aliasMap.get(canonicalName);
			if (resolvedName != null) {
				canonicalName = resolvedName;
			}
		}
		while (resolvedName != null);
		return canonicalName;
	}

}
